<template>
  <input
    type="text"
    :placeholder="placeholder"
    @input="searchChangeIpt"
    @keyup.enter="searchBtnClick"
    @compositionend="flog = false"
    @compositionstart="flog = true"
    v-model="searchValue"
    v-focus
  />
  <span>
    <button @click="searchBtnClick">搜索</button>
    <button @click="handleClearClick" class="clear-btn" v-show="showClearBtn"></button>
  </span>
</template>

<script lang="ts">
import { defineComponent, reactive, ref, toRefs, watch } from 'vue'

export default defineComponent({
  name: 'SearchInput',
  directives: {
    focus: {
      mounted(el: HTMLElement): void {
        el.focus()
      }
    }
  },
  props: {
    placeholder: {
      type: String,
      default: '请输入您要搜索的内容...'
    }
  },
  emits: ['schIptVN', 'searchBtnClick'],
  setup(props, { emit }) {
    const data = reactive({
      searchValue: '',
      showClearBtn: false,
      flog: false
    })

    watch(
      () => data.searchValue,
      (newValue) => (newValue.length > 0 ? (data.showClearBtn = true) : (data.showClearBtn = false))
    )

    const methods = {
      searchChangeIpt: () => {
        if (!data.flog && data.searchValue.length <= 0) {
          data.showClearBtn = false
          emit('schIptVN')
        }
      },

      searchBtnClick: (): void => {
        emit('searchBtnClick', data.searchValue)
      },

      handleClearClick: (): void => {
        data.searchValue = ''
        data.showClearBtn = false
        emit('schIptVN')
      }
    }

    return {
      ...toRefs(props),
      ...toRefs(data),
      ...methods
    }
  }
})
</script>

<style lang="stylus" scoped>
input,
button
  height 4rem
  transform translateY(-50%)
  vertical-align text-top
  font-size 1.4rem
  min-height 30px
  outline none
input
  width 25rem
  min-width 185px
  color #9e9c9c
  padding 0 5rem 0 1rem
  background-color #f9f0da
  border .2rem solid #7ba7ab
  border-radius .5rem
  box-shadow 0 .2rem .5rem #330033
  transition all 1s ease
  &:focus
    width 30rem
    color black
    box-shadow 0 .2rem .5rem #330033 inset
button
  margin-left -1.2rem
  line-height 100%
  background-color #7ba7ab
  border 1px solid transparent
  border-radius 0 .5rem 1.5rem 0
  cursor pointer
  transition all .3s
  &:hover
    color #f9f0da
    border-radius 0 1.5rem 1.5rem 0
    background-color #3d8f84
    box-shadow 0 .2rem .5rem #330033 inset
span
  position relative
  .clear-btn
    position absolute
    top 0
    left -2.7rem
    height 2rem
    min-height 12px
    width @height
    border 0
    border-radius 50%
    background-size 100%
    background-color #f9f0da
    background-image url('~@/assets/img/close.svg')
    background-repeat no-repeat
</style>
